package org.beyondhc.test;

import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;

/**
 * Helper class that attaches a mock to listen what is logged.
 * 
 * @author Jaana Kulmala
 * 
 */
public class LogMsgCaptor {

    private final transient Handler logHandlerMock;

    public LogMsgCaptor(final Logger logger) {
        this.logHandlerMock = Mockito.mock(Handler.class);
        logger.addHandler(logHandlerMock);
    }

    /**
     * @return latest logged message
     */
    public String getMsg() {
        final ArgumentCaptor<LogRecord> argument = ArgumentCaptor
                .forClass(LogRecord.class);
        Mockito.verify(logHandlerMock).publish(argument.capture());
        final LogRecord logRecord = argument.getValue();
        return logRecord.getMessage();
    }

    /**
     * Gets the nth logged message
     * 
     * @param count
     *            of the message to be returned
     * @param totalMsgCount
     *            total count of messages logged
     * @return nth logged message
     */
    public String getMsg(final int count, final int totalMsgCount) {
        final ArgumentCaptor<LogRecord> argument = ArgumentCaptor
                .forClass(LogRecord.class);
        Mockito.verify(logHandlerMock, Mockito.times(totalMsgCount)).publish(
                argument.capture());
        final List<LogRecord> logRecords = argument.getAllValues();
        final int index = count - 1;
        String msg = "";
        if (index >= 0 && index < logRecords.size()) {
            msg = logRecords.get(index).getMessage();
        }
        return msg;
    }

    /**
     * Verifies that nothing was logged
     */
    public void verifyNothingLogged() {
        Mockito.verifyNoMoreInteractions(logHandlerMock);
    }
}
